package com.huo.importdata.service;

import com.huo.annotation.TaskLogAnnotation;
import com.huo.common.dao.TableIndexMapper;
import com.huo.common.enumtype.FtpFileStatusEnum;
import com.huo.filestransport.dao.FtpFileInfoDao;
import com.huo.filestransport.entity.FtpFileInfoEntity;
import com.huo.filestransport.vo.FtpServerInfo;
import com.huo.importdata.dao.CdfmMapper;
import com.huo.importdata.entity.Cdfm;
import com.huo.util.DateUtils;
import com.huo.util.FileSplit;
import org.quartz.DisallowConcurrentExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.*;

@Service
@DisallowConcurrentExecution
public class ImportDataCdfmService {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private FtpFileInfoDao ftpFileInfoDao;
    @Autowired
    private CdfmMapper cdfmMapper;
    @Autowired
    private FileSplit fileSplit;
    @Autowired
    private TableIndexMapper tableIndexMapper;

    private final static int insertBatchNum = 400;

    @Autowired
    private FtpServerInfo ftpServerInfo;

    @TaskLogAnnotation
    public void importCdfm(){
        String dataDate = DateUtils.DateCount(ftpServerInfo.getDelayTime(),"yyyy-MM-dd");
        importCdfmByDate(dataDate);
    }


    public void importCdfmByDate(String datadate){
        logger.info("导入cdfm数据开始" );
        try {
            FtpFileInfoEntity record = new FtpFileInfoEntity();
            record.setFtpfilestatus(FtpFileStatusEnum.FTPFIEL_STATUS_UNZIP.getCode());
            record.setFtpfilename("S01_CDFM21.zip");
            record.setDataDateStr(datadate);
            FtpFileInfoEntity ffe = ftpFileInfoDao.selectBySelective(record);
            if(ffe != null) {
                //将表中数据删除
                cdfmMapper.truncateTableCdfm();
                Map<String,Object> map = new HashMap<>();
                map.put("tablename","T_TEMP_CDFM");
                map.put("indexname","T_TEMP_CDFM_KCRDNUM");
                tableIndexMapper.dropIndex(map);
                logger.info("导入S01_CDFM21数据开始" );
                String unzipfilePaht = ffe.getUnzipfilepath();
                long startT = System.currentTimeMillis();
                BufferedInputStream fis = null;
                BufferedReader reader = null;
                try {
                    long start = System.currentTimeMillis();
                    File file = new File(unzipfilePaht);
                    fis = new BufferedInputStream(new FileInputStream(file));
                    reader = new BufferedReader(new InputStreamReader(fis, "utf-8"), 20 * 1024 * 1024);
                    String line = "";
                    int dataNum = 0;
                    //插入次数
                    int insertNum = 0;
                    List<Cdfm> list = new ArrayList<>();
                    while ((line = reader.readLine()) != null) {
                        String[] str = line.split("\u001B");
                        //System.out.println(Arrays.toString(str));
                        Cdfm cdfm = new Cdfm();
                        cdfm.setKcrdnum(str[0]);
                        cdfm.setKacctyp(str[1]);
                        cdfm.setKacct(str[2]);
                        cdfm.setKaccs(str[3]);
                        cdfm.setKavaflg(str[4]);
                        list.add(cdfm);
                        if (list.size() == insertBatchNum) {
                            cdfmMapper.insertBatch(list);
                            list.clear();
                            insertNum++;
                        }
                        dataNum++;
                    }
                    if (dataNum != insertNum * insertBatchNum) {
                        cdfmMapper.insertBatch(list);
                    }
                    long end = System.currentTimeMillis();
                    logger.info("导入S01_CDFM21数据{}",dataNum);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        reader.close();
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                long endT = System.currentTimeMillis();
                logger.info("导入S01_CDFM21数据结束 ，导入数据时间：{}" ,endT - startT);
                FtpFileInfoEntity param = new FtpFileInfoEntity();
                param.setId(ffe.getId());
                param.setFtpfilestatus(FtpFileStatusEnum.FTPFIEL_STATUS_IMPORT.getCode());
                param.setUpdatetime(new Date());
                ftpFileInfoDao.updateByPrimaryKeySelective(param);
                map.put("tablecloum","KCRDNUM");
                tableIndexMapper.createIndex(map);
            }else{
                logger.info("未查询到S01_CDFM21.zip文件" );
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("导入cdfm数据结束" );
    }

}
